package com.zzt.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzt.common.BaseContext;
import com.zzt.common.R;
import com.zzt.domain.OrderDetail;
import com.zzt.domain.Orders;
import com.zzt.domain.dto.OrdersDto;
import com.zzt.service.OrderDetailService;
import com.zzt.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        //提交过来的只有几个信息,其它信息我们根据用户id来查,如购物车信息
        log.info("订单提交:{}", orders);
        orderService.submit(orders);
        return R.success("订单提交成功");
    }

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 查看历史订单
     * @return
     */
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(Integer page, Integer pageSize) {
        Long userId = BaseContext.getCurrentId();
        log.info("查看历史订单,userId={}", userId);
        //构造分页构造器
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null, Orders::getUserId, userId);
        orderService.page(ordersPage, wrapper);

        //开始拷贝
        Page<OrdersDto> ordersDtoPage = new Page<>(page, pageSize);
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        List<Orders> records = ordersPage.getRecords();
        List<OrdersDto> newRecords = new ArrayList<>();
        OrdersDto ordersDto;
        LambdaQueryWrapper<OrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
        for (Orders record : records) {
            orderDetailWrapper.clear();
            //根据每条Orders信息,查询其多个OrderDetail信息
            orderDetailWrapper.eq(OrderDetail::getOrderId, record.getId());
            List<OrderDetail> list = orderDetailService.list(orderDetailWrapper);
            ordersDto = new OrdersDto();
            ordersDto.setOrderDetails(list);
            BeanUtils.copyProperties(record, ordersDto);
            newRecords.add(ordersDto);
        }

        ordersDtoPage.setRecords(newRecords);

        return R.success(ordersDtoPage);
    }

    /**
     * 管理端订单明细
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime 前端get请求，因此不能用对象接+@JsonFormat注解属性来接
     * @param endTime 因此这两个时间先用String接，再做处理。这两个数据必同时为null或非null
     * @return
     */
    @GetMapping("/page")
    public R<Page<Orders>> page(int page, int pageSize, Integer number, String beginTime, String endTime) {
        log.info("订单明细,page={},pageSize={},number={},beginTime={},endTime={}", page, pageSize, number, beginTime, endTime);
        //构造分页构造器
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        //对两个时间进行转换。
        //String与Date日期格式转换,由于Date格式是如Wed Mar 01 00:00:00 CST 2023的，因此不合适，要用LocalDateTime
        //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //String与LocalDateTime日期格式转换,才能匹配上数据库的日期格式。
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        LocalDateTime beginDate = null, endDate = null;
        if (beginTime != null && endTime != null) {
            /*try {
                beginDate = simpleDateFormat.parse(beginTime);
                endDate = simpleDateFormat.parse(beginTime);
            } catch (Exception e) {
                throw new CustomException(e.getMessage());
            }*/
            beginDate = LocalDateTime.parse(beginTime, formatter);
            endDate = LocalDateTime.parse(endTime, formatter);
        }
        //System.out.println("检查日期格式有无问题：beginDate=" + beginDate + " endDate=" + endDate);
        //构造条件构造器
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(number != null, Orders::getNumber, number);//创建order的时候其实number是直接用的id，所以值一样的，只不过一个是订单号，一个是主键。
        wrapper.between(beginDate != null && endDate != null, Orders::getOrderTime, beginDate, endDate);
        //MP分页查询
        orderService.page(ordersPage, wrapper);
        return R.success(ordersPage);
    }

    /**
     * 派送/完成/取消 订单，即修改订单status为3/4/5
     * @return
     */
    @PutMapping
    public R<String> delivery(@RequestBody Orders orders){
        log.info("派送订单,订单id={}",orders.getId());
        /*LambdaQueryWrapper<Orders> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(orders.getId()!=null,Orders::getNumber,orders.getId());
        orderService.update(orders,wrapper);*/
        orderService.updateById(orders);

        String message="";
        if(orders.getStatus()==3) message="订单开始派送";
        else if(orders.getStatus()==4) message="订单已完成";
        else message="订单已取消";
        return R.success(message);
    }

}
